Vue.component('add-node', {//添加菜单组件
    template: `<el-dialog :title="form.Level==1?'添加菜单':'添加子菜单'" :visible.sync="visibleDialog" width="700px" :close-on-click-modal="false" destroy-on-close>
    <el-form ref="contract" :model="form" :rules="rules" :inline-message="true">
        <el-descriptions :column="1" border size="small">
            <el-descriptions-item label="父级菜单">
                <el-form-item prop="Model_Name">
                    <el-cascader @change="handleParent" v-model="form.Parent_Number" style="width:100%" placeholder="可选择父级菜单" :options="options" :props="{label:'Model_Name',value:'Model_Number', checkStrictly: true, emitPath:false }" clearable></el-cascader>
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="菜单名称">
                <el-form-item prop="Model_Name">
                    <el-input v-model.trim="form.Model_Name" placeholder="请输入菜单名称"></el-input>
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="菜单顺序">
                <el-form-item prop="Order">
                    <el-input v-model.trim="form.Order" placeholder="请输入菜单顺序"></el-input>
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="页面路径">
                <el-form-item prop="Url">
                    <el-input v-model.trim="form.Url" placeholder="可输入页面路径"></el-input>
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item v-if="form.Level==1" label="菜单图标">
                <el-form-item prop="Icon">
                    <el-select placeholder="请选择菜单图标" style="width: 100%;" clearable filterable v-model.trim="form.Icon">
                        <el-option v-for="(item,index) in Icon" :key="index" :label="item" :value="'layui-icon '+item">
                            <i class="layui-icon" :class="item"></i>
                            <i>{{item}}</i>
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-descriptions-item>
        </el-descriptions>
    </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button @click="$emit('update:visible',false)">取消</el-button>
        <el-button :loading="loading" type="primary" @click="submitForm('contract')">提交</el-button>
    </span></el-dialog>`,
    props: ['data', 'page', 'visible'],
    data() {
        return {
            visibleDialog: false,
            Icon: [],//图标库
            form: {
                Model_Number: '',
                ...this.data,
                Icon: '',
                Model_Name: '',
            },
            rules: {
                Model_Name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
                Order: [{ required: true, message: '请输入菜单顺序', trigger: 'blur' }],
                Icon: [{ required: true, message: '请选择菜单图标', trigger: 'change' }]
            },
            loading: false,
            role: []
        }
    },
    watch: {
        visible() {
            this.visibleDialog = this.visible
        },
        visibleDialog(val) {
            this.$emit('update:visible', val)
        },
        'data.Parent_Number': function (newVal) {
            this.form.Parent_Number = newVal;
        },
        'data.Level': function (newVal) {
            this.form.Level = newVal;
        }
    },
    computed: {
        options() {
            let arr = this.page.map(obj => {
                return deepClone(obj);
            })
            this.configTree(arr);
            return arr;
        }
    },
    methods: {
        configTree(arr) {
            arr.forEach(item => {
                if (item.Url != '') {
                    item.disabled = true;
                    delete item.children;
                } else if (item.children && item.children.length > 0) {
                    this.configTree(item.children);
                }
            })
        },
        handleParent(val) {
            if (val == null) {
                this.form.Parent_Number = '';
                this.form.Level = 1;
            } else {
                let obj = this.getParent(this.page, val);
                if (obj) {
                    this.form.Level = parseInt(obj.Level) + 1;
                    this.form.Icon = '';
                }
            }
        },
        getParent(arr, val) {
            for (let i = 0; i < arr.length; i++) {
                const item = arr[i];
                if (item.Model_Number === val) {
                    return item;
                } else if (item.children && item.children.length > 0) {
                    let obj = this.getParent(item.children, val);
                    if (obj) {
                        return obj;
                    }
                }
            }
        },
        async getData() {
            this.role = await generalApi.generalFilePath('role.json');
            $.ajax({
                url: absolutepath() + 'admin/data/icon.json',
                type: 'GET',
                success: (data) => {
                    this.Icon = data;
                },
            })
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.loading = true;
                    httpRequest({
                        url: '/generalBusiness/generalQueryByTableName',
                        data: {
                            Data: 'base_system_user_info',
                            Condition: `Row_Status='0' AND Developer='1'`
                        },
                        type: 'GET'
                    }).then(data => {
                        let role = new Object();
                        this.role.forEach(i => {
                            role[i.value] = '1'
                        })
                        //自动给开发者加菜单权限
                        let base_system_rights_user_model = data.map(i => {
                            return {
                                User_Number: i.User_Number,
                                UR_Page: '1111',
                                ...role
                            }
                        })
                        if (base_system_rights_user_model.length > 0) {
                            this.form.Children = { base_system_rights_user_model }
                        }
                        let lJSONObject_DataSet = {
                            Add: { base_system_model_list: [this.form] }
                        }
                        let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                        lJSONObject_DataSet['Add']['base_operation_log'] = [{
                            Operation_Type: '0',
                            Operation_Path: getRelativePath(),
                            Operation_Description: '添加菜单数据',
                            Operation_Main,
                            Operation_Interface: "generalSaveByRequestBody",
                            Operation_IP: getIpAddress()
                        }]
                        httpRequest({
                            contentType: 'JSON',
                            url: '/generalBusiness/generalSaveByRequestBody',
                            data: JSON.stringify({
                                Data: lJSONObject_DataSet
                            })
                        }).then(res => {
                            if (res.Status == 'success') {
                                this.$emit('update:visible', false);
                                this.$message.success("提交成功");
                                this.form = { ...this.data, Icon: '', Model_Name: '', }
                                this.$emit('success')
                            } else {
                                this.$message.error("提交失败，请稍后再试")
                            }
                        }).catch(xhr => {
                            this.$message({
                                message: '系统错误，请联系开发者!',
                                type: 'error'
                            })
                        }).finally(() => {
                            this.loading = false;
                        });

                    }).catch(xhr => {
                        this.loading = false;
                        this.$message.error("系统错误，请联系开发者!")
                    })
                } else {
                    this.$message({
                        message: '存在未填写的必填项！',
                        type: 'warning'
                    })
                    return false;
                }
            })
        }
    },
    mounted() {
        this.getData();
    }
})

Vue.component('edit-node', {//修改菜单组件
    template: `<el-dialog title="修改菜单" :visible.sync="visibleDialog" width="700px" :close-on-click-modal="false">
    <el-form ref="contract" :model="form" :rules="rules" :inline-message="true">
        <el-descriptions :column="1" border size="small">
            <el-descriptions-item label="父级菜单">
                <el-form-item prop="Model_Name">
                    <el-cascader @change="handleParent" v-model="form.Parent_Number" style="width:100%" placeholder="可选择父级菜单" :options="options" :props="{label:'Model_Name',value:'Model_Number', checkStrictly: true, emitPath:false }" clearable></el-cascader>
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="菜单名称">
                <el-form-item prop="Model_Name">
                    <el-input v-model.trim="form.Model_Name" placeholder="请输入菜单名称"></el-input>
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="菜单顺序">
                <el-form-item prop="Order">
                    <el-input v-model.trim="form.Order" placeholder="请输入菜单顺序"></el-input>
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="页面路径" v-if="isUrl">
                <el-form-item prop="Url">
                    <el-input v-model.trim="form.Url" placeholder="可输入页面路径"></el-input>
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item v-if="form.Level==1" label="菜单图标">
                <el-form-item prop="Icon">
                    <el-select placeholder="请选择菜单图标" style="width: 100%;" clearable filterable v-model.trim="form.Icon">
                        <el-option v-for="(item,index) in Icon" :key="index" :label="item" :value="'layui-icon '+item">
                            <i class="layui-icon" :class="item"></i>
                            <i>{{item}}</i>
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-descriptions-item>
        </el-descriptions>
    </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button @click="$emit('update:visible',false)">取消</el-button>
        <el-button :loading="loading" type="primary" @click="submitForm('contract')">提交</el-button>
    </span></el-dialog>`,
    props: ['data', 'page', 'visible'],
    data() {
        return {
            visibleDialog: false,
            Icon: [],//图标库
            form: this.data,
            isUrl: true,
            rules: {
                Model_Name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
                Order: [{ required: true, message: '请输入菜单顺序', trigger: 'blur' }],
                Icon: [{ required: true, message: '请选择菜单图标', trigger: 'change' }]
            },
            loading: false,
        }
    },
    watch: {
        visible() {
            this.visibleDialog = this.visible;

        },
        visibleDialog(val) {
            this.$emit('update:visible', val)
        },
        data: {
            handler(newVal) {
                this.isUrl = newVal.childNodes == 0 ? true : false;
                this.form = { Level: parseInt(newVal.Level) };
                this.loading = true;
                httpRequest({
                    url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                    data: {
                        Data: 'base_system_model_list',
                        Condition: `Model_Number='${newVal.Model_Number}'`,
                    }
                }).then(data => {
                    if (data.length == 1) {
                        this.form = data[0];
                    }
                }).catch(xhr => {
                    this.$message({
                        message: '系统错误，请联系开发者!',
                        type: 'error'
                    })
                }).finally(() => {
                    this.loading = false;
                })
            },
            deep: true // 深度监听  
        },
    },
    computed: {
        options() {
            let arr = this.page.map(obj => {
                return deepClone(obj);
            })
            this.configTree(arr);
            return arr;
        }
    },
    methods: {
        configTree(arr) {
            arr.forEach(item => {
                if (item.Url != '') {
                    item.disabled = true;
                    delete item.children;
                } else if (item.children && item.children.length > 0) {
                    this.configTree(item.children);
                }
            })
        },
        getData() {
            $.ajax({
                url: absolutepath() + 'admin/data/icon.json',
                type: 'GET',
                success: (data) => {
                    this.Icon = data;
                },
            })
        },
        handleParent(val) {
            if (val == null) {
                this.form.Parent_Number = '';
                this.form.Level = 1;
            } else {
                let obj = this.getParent(this.page, val);
                if (obj) {
                    this.form.Level = parseInt(obj.Level) + 1;
                    this.form.Icon = '';
                }
            }
        },
        getParent(arr, val) {
            for (let i = 0; i < arr.length; i++) {
                const item = arr[i];
                if (item.Model_Number === val) {
                    return item;
                } else if (item.children && item.children.length > 0) {
                    let obj = this.getParent(item.children, val);
                    if (obj) {
                        return obj;
                    }
                }
            }
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.loading = true;
                    httpRequest({
                        url: '/generalBusiness/queryMultiTableByCondition',
                        data: {
                            Data: JSON.stringify([{
                                tableName: "base_column_config",
                                Condition: utf8ToBase64(`Model_Url='${this.form.Url_Original}' AND Model_Url<>''`),
                            }, {
                                tableName: 'base_sql_list',
                                Condition: utf8ToBase64(`Model_Url='${this.form.Url_Original}' AND Model_Url<>''`),
                            }])
                        },
                    }).then(({ base_column_config, base_sql_list }) => {
                        base_column_config.forEach(item => {
                            item.Model_Url = this.form.Url;
                        })
                        base_sql_list.forEach(item => {
                            item.Model_Url = this.form.Url;
                        })

                        let lJSONObject_DataSet = {
                            Modify: {
                                base_system_model_list: [this.form],
                                base_column_config, base_sql_list
                            }, Add: {}
                        }
                        
                        let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                        lJSONObject_DataSet['Add']['base_operation_log'] = [{
                            Operation_Type: '0',
                            Operation_Path: getRelativePath(),
                            Operation_Description: '修改菜单数据',
                            Operation_Main,
                            Operation_Interface: "generalSaveByRequestBody",
                            Operation_IP: getIpAddress()
                        }]
                        httpRequest({
                            contentType: 'JSON',
                            url: '/generalBusiness/generalSaveByRequestBody',
                            data: JSON.stringify({
                                Data: lJSONObject_DataSet
                            })
                        }).then(res => {
                            if (res.Status == 'success') {
                                this.$emit('update:visible', false);
                                this.$message.success("修改成功");
                                this.form = {};
                                this.$emit('success');
                            } else {
                                this.$message.error("提交失败，请稍后再试")
                            }
                        }).catch(xhr => {
                            this.$message({
                                message: '系统错误，请联系开发者!',
                                type: 'error'
                            })
                        }).finally(() => {
                            this.loading = false;
                        });
                    }).catch(xhr => {
                        this.loading = false;
                        this.$message.error("系统错误，请联系开发者!")
                    })
                } else {
                    this.$message({
                        message: '存在未填写的必填项！',
                        type: 'warning'
                    })
                    return false;
                }
            })
        }
    },
    mounted() {
        this.getData();
    }
})
new Vue({
    el: '#app',
    data() {
        return {
            defaultProps: {
                children: 'children',
                label: 'Model_Name'
            },
            tableData: [],
            treeData: [],
            form: {//查询筛选
                value: '',
            },
            nodeData: {//添加
                Parent_Number: '',
                Level: 1,
                Url: ''
            },
            nodeEditData: {},//修改
            loading: false,
            dialogVisible: false,
            dialogEditVisible: false,
            page: [],
            buttonRole:[]
        }
    },
    mounted() {
        this.getData();
    },
    methods: {
        handleSerach() {
            this.tableData = this.Recursion(this.treeData);
        },
        Recursion(lArray_TreeData) {
            // 创建一个副本，避免在遍历时修改原数组
            const result = [];
            for (let i = 0; i < lArray_TreeData.length; i++) {
                const lJSONObject_Record = lArray_TreeData[i];
                const lJSONArray_Children = lJSONObject_Record.children || [];
                // 递归处理子节点
                const filteredChildren = this.Recursion(lJSONArray_Children);
                // 如果当前节点名称匹配搜索条件，或者有匹配的子节点，则保留
                const nameMatch = lJSONObject_Record.Model_Name.includes(this.form.value);
                const hasChildren = filteredChildren.length > 0;
                if (nameMatch || hasChildren) {
                    // 创建一个新对象，避免修改原数据
                    const newNode = { ...lJSONObject_Record };
                    newNode.children = filteredChildren;
                    result.push(newNode);
                }
            }
            return result;
        },
        handleAdd(node, data) {
            if (!data || data.Url == '') {
                if (node && data) {
                    this.nodeData.Parent_Number = data.Model_Number;
                    this.nodeData.Level = node.level + 1;
                } else {
                    this.nodeData.Parent_Number = '';
                    this.nodeData.Level = 1;
                }
                this.dialogVisible = true;
            } else {
                sessionStorage.setItem("Url", data.Url);
                if (data.SQL_SerialNumber) {
                    window.location.href = "../sql/sql_config.html?action=Modify&nodeKey=" + data.SQL_SerialNumber;
                } else {
                    window.location.href = "../sql/sql_config.html?action=Add";
                }
            }
        },
        async getData() {
            try {
                const [data, role] = await Promise.all([
                    httpRequest({
                        url: '/generalBusiness/getMenuList',
                        type: 'GET',
                    }),
                    generalApi.generalQueryBySQLSerialNumber({
                        SQLSerialNumber: 's_base_button_config',
                        Condition: utf8ToBase64(`${getCookie('user')},${getRelativePath()}`),
                        ExtensionCondition: ''
                    }),
                ]);
                this.buttonRole = Object.entries(role[0] || {}).reduce((acc, [key, value]) => {
                    acc[key] = value === '1'; // 1 → true, 0 → false
                    return acc;
                }, {});
                this.tableData = data;
                this.treeData = data;
            } catch (error) {
                console.error(error);
                this.$message({
                    message: '系统错误，请联系开发者!',
                    type: 'error'
                })
            }
        },
        handleEdit(node, row) {
            this.nodeEditData = row;
            this.nodeEditData.childNodes = node.childNodes.length
            this.dialogEditVisible = true;
        },
        handleRemove(row) {
            this.$confirm('警告！此操作将删除该菜单节点, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                httpRequest({
                    url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                    data: {
                        Data: "base_system_model_list",
                        Condition: "Model_Number='" + row.Model_Number + "'"
                    }
                }).then(data => {
                    if (data.length == 1) {
                        data[0].Row_Status = '1';
                        let lJSONObject_DataSet = {
                            Modify: { base_system_model_list: data }, Add: {}
                        }
                        let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                        lJSONObject_DataSet['Add']['base_operation_log'] = [{
                            Operation_Type: '0',
                            Operation_Path: getRelativePath(),
                            Operation_Description: '删除菜单数据',
                            Operation_Main,
                            Operation_Interface: "generalSaveByRequestBody",
                            Operation_IP: getIpAddress()
                        }]
                        httpRequest({
                            contentType: 'JSON',
                            url: '/generalBusiness/generalSaveByRequestBody',
                            data: JSON.stringify({
                                Data: lJSONObject_DataSet
                            })
                        }).then(res => {
                            if (res.Status == "success") {
                                this.getData();
                                this.$message.success("删除成功");
                            } else {
                                this.$message.error("删除失败，请重试！");
                            }
                        }).catch(xhr => {
                            this.$message({
                                message: '系统错误，请联系开发者!',
                                type: 'error'
                            })
                        })
                    }
                }).catch(xhr => {
                    this.$message({
                        message: '系统错误，请联系开发者!',
                        type: 'error'
                    })
                })
            }).catch(() => { });
        }
    }
})